<template>
    <div class="search-div">
        <!-- 搜索表单 -->
        <el-form label-width="70px" size="small">
            <el-form-item label="岗位名称">
                <el-input v-model="role.pname" style="width: 120px" placeholder="岗位名称"></el-input>
            </el-form-item>
            <el-row style="display:flex">
                <el-button type="primary" size="small" @click="searchSysRole">
                    搜索
                </el-button>
                <el-button size="small" @click="resetData">重置</el-button>
            </el-row>
        </el-form>

        <!-- 添加按钮 -->
        <div class="tools-div">
            <el-button type="success" size="small" @click="addShow">添 加</el-button>
        </div>
        <!-- 添加角色表单对话框 -->
        <!-- 页面表单 -->
        <el-dialog v-model="dialogVisible" title="添加或修改岗位" width="30%">
            <el-form label-width="120px">

                <el-form-item label="角色名称">
                    <el-input v-model="role.pname" />
                </el-form-item>
                <el-form-item label="描述">
                    <el-input v-model="role.describe" />
                </el-form-item>
                <el-form-item label="所属部门">
                    <el-cascader :props="categoryProps" v-model="role.parentId" />
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="submit">提交</el-button>
                    <el-button @click="diso">取消</el-button>
                </el-form-item>
            </el-form>
        </el-dialog>
        <!--分配角色-->
        <el-dialog v-model="dialogRoleVisible" title="分配角色" width="40%">
            <el-form label-width="80px">
                <el-form-item label="用户名">
                    <el-input disabled :value="role.pname"></el-input>
                </el-form-item>

                <el-form-item label="角色列表">
                    <el-checkbox-group v-model="userRoleIds">
                        <el-checkbox v-for="role in allRoles" :key="role.id" :label="role.id">
                            {{ role.roleName }}
                        </el-checkbox>
                    </el-checkbox-group>
                </el-form-item>

                <el-form-item>
                    <el-button type="primary" @click="doAssign">提交</el-button>
                    <el-button @click="dialogRoleVisible = false">取消</el-button>
                </el-form-item>
            </el-form>
        </el-dialog>


        <!--- 角色表格数据 -->
        <el-table :data="list" style="width: 100%">
            <el-table-column prop="pname" label="角色名称" width="120" />
            <el-table-column prop="describe" label="描述" width="220" />
            <el-table-column prop="title" label="所属部门" width="120" />
            <el-table-column prop="createTime" label="创建时间" width="120" />
            <el-table-column prop="updateTime" label="修改时间" width="120" />
            <el-table-column label="操作" align="center" width="280" #default="scope">
                <el-button type="primary" size="small" @click="editShow(scope.row)">
                    修改
                </el-button>
                <el-button type="danger" size="small" @click="deleteById(scope.row)">
                    删除
                </el-button>
                <el-button type="warning" size="small" @click="showAssignRole(scope.row)">
                    分配角色
                </el-button>
            </el-table-column>
        </el-table>

        <el-pagination v-model:current-page="pageParams.page" v-model:page-size="pageParams.limit"
            :page-sizes="[5, 10, 20, 50, 100]" @size-change="fetchData" @current-change="fetchData"
            layout="total, sizes, prev, pager, next" :total="total" />
    </div>

</template>

<!-- script部分修改内容 -->
<script setup>
import { ref, onMounted } from 'vue';
import { FindCategoryByParentId } from '@/api/limits/kywDepartment'
import { selectPost, addPost, updatePost, deletePost, selectPostCount } from "@/api/limits/kywPost";
import { GetRoleAll } from "@/api/limits/kywRole";
import { addUserRole } from "@/api/limits/kywuser"
import { FindNodes } from '@/api/limits/kywDepartment'
import { ElMessage, ElMessageBox } from 'element-plus'
// 分页条总记录数
let total = ref(0)

// 定义表格数据模型
let list = ref([])
const defaultProps = {
    children: 'children',
    label: 'title',
}
const sysMenuTreeList = ref([])
//分页数据
const pageParamsForm = {
    page: 1, // 页码
    limit: 5, // 每页记录数
}
const pageParams = ref(pageParamsForm)     // 将pageParamsForm包装成支持响应式的对象

//=============所属部门==================
const props = {
    lazy: true,
    value: 'id',
    label: 'title',
    leaf: 'leaf',
    async lazyLoad(node, resolve) {   // 加载数据的方法
        if (typeof node.value == 'undefined') node.value = 0
        const { data } = await FindCategoryByParentId(node.value)
        data.forEach(function (item) {       //hasChildren判断是否有子节点
            item.leaf = !item.hasChildren
        })
        resolve(data)  // 返回数据  
    }
};

const categoryProps = ref(props)


//==================================

//定义用户数据模型
const defaultForm = {
    id: "",
    pname: "",
    status: "",
    parentId: null,
    title: "",
    describe: "",
    createTime: "",
    updateTime: "",
}
const role = ref(defaultForm)

// 页面加载完毕以后请求后端接口获取数据
onMounted(() => {
    fetchData()
})

// 搜索按钮点击事件处理函数
const searchSysRole = () => {
    fetchData();
}

// 重置按钮点击事件处理函数
const resetData = () => {
    role.value.roleName = ""
    fetchData();
}


// 远程调用后端分页查询接口
const fetchData = async () => {
    const { data, code, message } = await selectPost(pageParams.value.page, pageParams.value.limit, role.value);
    console.log(data.list);
    list.value = data.list;
    total.value = data.total
}

//添加
// 控制对话是否展示的变量
const dialogVisible = ref(false)
const diso = () => {
    dialogVisible.value = false
    role.value = {}
}
//进入添加
const addShow = () => {
    dialogVisible.value = true
    role.value = {}
}


//提交
const submit = async () => {
    if (!role.value.id) {
        const st = role.value.parentId.length - 1
        role.value.parentId = role.value.parentId[st]
        const { code } = await addPost(role.value);
        console.log(role.value);
        if (code === 200) {
            dialogVisible.value = false
            ElMessage.success('添加成功')
            role.value = {}
            fetchData()
        }
    } else {
        const st = role.value.parentId.length - 1
        role.value.parentId = role.value.parentId[st]
        console.log(role.value);
        const { code } = await updatePost(role.value);
        if (code === 200) {
            dialogVisible.value = false
            ElMessage.success('修改成功')
            role.value = {}
            resetData()
        }
    }
}
//删除
const deleteById = (row) => {
    ElMessageBox.confirm('此操作将永久删除该记录, 是否继续?', 'Warning', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
    }).then(async () => {
        const { data, code } = await selectPostCount(row.id)
        if (data == 0) {
            const { code } = await deletePost(row.id)
            if (code === 200) {
                ElMessage.success('删除成功')
                pageParams.value.page = 1
                fetchData()
            }
        } else {
            ElMessageBox.confirm('该岗位关联多个用户，请取消关联后再删除?', 'Warning', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
            })
        }

    })
}
//修改回显
const editShow = (row) => {
    dialogVisible.value = true
    role.value = row
}

// 角色列表
const userRoleIds = ref([])
const allRoles = ref([])
const dialogRoleVisible = ref(false)
const showAssignRole = async row => {
    role.value = row
    dialogRoleVisible.value = true
    // 查询所有的角色数据
    const { code, message, data } = await GetRoleAll(row.id);
    allRoles.value = data.allRolesList
    // 获取当前登录用户的角色数据
    userRoleIds.value = data.kywUserRoles
}
// 角色分配按钮事件处理函数
const doAssign = async () => {
    let assginRoleVo = {
        id: role.value.id,
        roleIdList: userRoleIds.value
    }
    const { code, message, data } = await addUserRole(assginRoleVo);
    if (code === 200) {
        ElMessage.success('操作成功')
        dialogRoleVisible.value = false
        fetchData()
    }
}


</script>

<style scoped>
.search-div {
    margin-bottom: 10px;
    padding: 10px;
    border: 1px solid #ebeef5;
    border-radius: 3px;
    background-color: #fff;
}

.tools-div {
    margin: 10px 0;
    padding: 10px;
    border: 1px solid #ebeef5;
    border-radius: 3px;
    background-color: #fff;
}

.avatar-uploader .avatar {
    width: 178px;
    height: 178px;
    display: block;
}

.avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
}
</style>